import useAlLayoutEffect from '@/layouts/hooks/alLayoutEffect'
import { LayoutMenu } from '@/layouts/hooks/getLayoutMenu'
import { useRouter, useRoute } from 'vue-router'
import { computed, ref } from 'vue'
import advancedMenuConfiguration from '@/layouts/advancedMenuConfiguration.json'
import DpaMenu from '@/layouts/dpaMenu.json'
import LayoutConfig from '@/layouts/layoutConfig.json'
import { find } from 'lodash-es'
import { useLayoutStore } from '@/store/modules/layout'
import { useSystemStore } from "@/store/modules/system";
import { getFullUrl } from "@/utils";
const systemStore = useSystemStore();

// @ts-ignore
export default function () {
  const { setMenuListByPermission } = useAlLayoutEffect({})
  const layoutStore = useLayoutStore()
  const layoutMap = layoutStore.getLayoutMap

  const router = useRouter()
  const route = useRoute()
  const layoutMenu = new LayoutMenu()

  const selectedKeys = computed(() => {
    const { fullPath, path, meta } = router.currentRoute.value;
    const breadcrumb = systemStore.currentBreadcrumbInfo;
    let _parent;
    let flag = true;
    for (const i in breadcrumb) {
      for (const j in breadcrumb[i]) {
        if (getFullUrl(breadcrumb[i][j]?.targetPage?.url) === path && j !== 0) {
          _parent = breadcrumb[i][j - 1];
          flag = false;
          break;
        }
      }
      if (!flag) {
        break;
      }
    }
    const fullPathCode = layoutMenu.getPathByCode(decodeURI(fullPath)) ?? layoutMenu.getPathByCode(fullPath)
    if (fullPathCode) {
      return [fullPathCode]
    } else if (_parent) {
      const { targetPage } = _parent
      const targetPageCode =
        layoutMenu.getPathByCode(decodeURI(getFullUrl(targetPage.url))) ??
        layoutMenu.getPathByCode(getFullUrl(targetPage.url))
      if (targetPage && targetPage.url && targetPageCode) {
        return [targetPageCode]
      }
    }
    return [meta.code];
  });

  const getMenuName = menuItem => {
    const { contentSetting, menuId } = menuItem
    const MENU_NAME_MAP = {
      FORM_LIST: 'menu_form_',
      TABLE_LIST: 'menu_table_',
      PAGE_LIST: 'menu_page_',
      SYSTEM_MENU: 'menu_system_',
      BI_DASH_BOARD: 'menu_bi_publish_',
      VISUALIZATION_LARGE_SCREEN: 'menu_visualization_publish_',
      ALLIN_RESOURCE_MENU: 'menu_resource_',
      CUSTOM_PAGE: 'menu_custom_page_'
    }

    if (!contentSetting.settingId) {
      return 'menu_page_' + menuId
    }
    if (contentSetting.settingType === 'CUSTOM_PAGE') {
      return MENU_NAME_MAP[contentSetting.settingType] + menuId
    } else {
      return MENU_NAME_MAP[contentSetting.settingType] + contentSetting.settingId
    }
  }
  // 获取布局id
  function getLayoutId(current: any, pageConfiguration: any) {
    const { layoutPageConfig } = pageConfiguration
    const layoutInfo = layoutPageConfig.filter((item: any) => {
      return current.menuUrl === item.menuUrl
    })
    return layoutInfo.length ? layoutInfo[0].layoutPlanId : ''
  }
  const isAdvancedLayout = ref(false)
  const advanceMenuInfo = ref<string[]>([]);

  // 构建菜单信息
  const buildMenuInfoAdvanced = (menuList: any, pageConfiguration: any) => {
    const menuListInfo: any = []
    menuList.forEach(item => {
      const name = getMenuName(item) + getLayoutId(item, pageConfiguration);

      const menuItem = {
        name,
        title: item?.title,
        code: item?.code ? item.code : '',
        icon: item?.icon,
        selectedIcon: item?.selectedIcon,
        children: [] as any[],
        iconDisplay: item?.iconDisplay,
        hideMenu: ['CUSTOM_PAGE', 'PRO_CODE_PAGE'].includes(item?.settingType) ? !item?.menuShow : false //定制化页面和自定义页面可配置显示菜单
      }

      if (item.menuExpandFlag) {
        advanceMenuInfo.value.push(name);
      }

      const children = buildMenuInfoAdvanced(item.children, pageConfiguration)
      if (children && children.length > 0) {
        menuItem.children = menuItem.children.concat(children)
      }
      menuListInfo.push(menuItem)
    })
    return menuListInfo.filter(item => !item.hideMenu)
  }

  const menuInfo = computed(() => {
    const {
      meta: { layoutPlanId: metaLayoutPlanId },
      fullPath,
      query
    } = route || { meta: {}, fullPath: '' }
    // 如果路由中携带了layoutPlanId参数，以路由中的参数为准
    let layoutPlanId = query && query.layoutPlanId ? query.layoutPlanId : metaLayoutPlanId

    if (!layoutPlanId && layoutMap) {
      const _currentLayout = find(layoutMap, { url: fullPath })
      if (_currentLayout) {
        layoutPlanId = _currentLayout.layoutPlanId
      }
    }

    let result = []

    // 如果有布局，获取布局方式
    if (layoutPlanId && layoutPlanId !== 'DPA_NAVIGATION_OTHER') {
      const { layoutConfiguration, pageConfiguration } = advancedMenuConfiguration
      const _currentLayout = find(layoutConfiguration, { id: layoutPlanId })
      if (_currentLayout && _currentLayout.layoutPlan !== 'DPA_NAVIGATION') {
        const menus = buildMenuInfoAdvanced(_currentLayout.menuConfigurationList, pageConfiguration)
        result = setMenuListByPermission(menus)
      } else {
        result = _currentLayout.dpaMenuConfiguration
      }
      isAdvancedLayout.value = true
    } else if (LayoutConfig.layoutPlan !== 'DPA_NAVIGATION') {
      const menuList = layoutMenu.menuInfo
      result = setMenuListByPermission(menuList) || []
    } else {
      result = DpaMenu
    }
    return result
  })

  const getAllParentId = (key: string): Array<string> => {
    const { parentId } = layoutMenu.codePathMap.get(key) || {}
    if (parentId) {
      const grandParentId = getAllParentId(parentId)
      return [parentId, ...grandParentId]
    } else {
      return []
    }
  }

  const [_selectedKeys] = selectedKeys.value
  const currentExpandKeys = getAllParentId(_selectedKeys)
  const menuExpandKeys = computed(() => {
    return [...new Set([...layoutMenu.menuExpandKeys, ...currentExpandKeys, ...advanceMenuInfo.value])]
  })

  return {
    selectedKeys,
    isAdvancedLayout,
    menuInfo,
    codePathMap: layoutMenu.codePathMap,
    menuExpandKeys
  }
}
